package com.tang.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库配置文件加解密工具
 *
 * @author Tang
 * @date 2024/1/24 18:45
 **/
public class DruidEncryptUtil {
    //公钥
    private static String publicKey;
    //私钥
    private static String privateKey;

    static {
        try {
            String[] keyPairs = ConfigTools.genKeyPair(512);
            privateKey = keyPairs[0];
            System.out.println("privateKey:" + privateKey);
            publicKey = keyPairs[1];
            System.out.println("publicKey:" + publicKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 利用私钥对字符串加密
     *
     * @param plainText 待加密的字符串
     * @return java.lang.String
     * @author Tang
     * @date 2024/1/24 18:54
     **/
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt:" + encrypt);
        return encrypt;
    }

    /**
     * 利用公钥对字符串解密
     *
     * @param encryptText 待加密的字符串
     * @return java.lang.String
     * @author Tang
     * @date 2024/1/24 18:54
     **/
    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt:" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
    }
}
